<?php

App::import('Model', 'Account');
class FutureTweetsController extends AppController{
    
  public $helpers = array('Html', 'Form');
  public $components = array('Session');
  var $uses = array('FutureTweet', 'Tweet', 'tattlrAccount','User' , 'Accounts_has_user' , 'Account');

  
/* Description of index function
	 * @return: void
     * The function index contains the view of the future timeline for a moderator
      and moderator is able to view in this page links for the names of editors and j.editors
     * @author: Amr Magdy
     */

    public function index() {

        $accID = $this->Auth->User('accID');
        $this->set('accID', $accID);
        $this->set('result', $this->FutureTweet->getUser($accID));

        $userID = $this->Auth->User('userID');
        $this->set('accid', $accID);
        $this->set('num', $this->FutureTweet->countPendingTweets());

        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == 1) {

            $user = new User;
            $this->set('e', $user->getEditorsByNameandid($accID));
            $this->set('je', $user->getJEditorsByNameandid($accID));
        } else {
            $this->redirect(array('action' => 'index1'));
        }
    }
  

  public function eventstweetstest($id = null)
  {

     $conditions = array("FutureTweet.eventID" => $id);
     return $this->FutureTweet->find('all',array('conditions' => $conditions));
  }

    /*
     * Description of index1
	 * @return: void
     * The function index1 contains the view of the future timeline for an editor or j.editor
     * @author Amr Magdy
     */

    public function index1() {

        $accID = $this->Auth->User('accID');
        $this->set('accID', $accID);


        $this->set('result', $this->FutureTweet->getUser($accID));
    }
  
  /**
   * description cron
   *to run the function postingTweet to post tweet on twitter
   *this function will be run through cron job
   *
   *@return void
   *
   * @author Youssef Madkour
   */
  
   public function cron() {
        $this->FutureTweet->postingTweet();
        
    }
  
  
    public function fetchTweet() {

    $current_time = date('Y-m-d H:i:s');
     
    $condition = array("FutureTweet.release_date" => $current_time);
    $tem=$this->FutureTweet->find('all',array('conditions' => $condition));
    $this -> set('FutureTweets',$this->FutureTweet->find('all',array('conditions' => $condition)));
    
    foreach ($tem as $t):
          
      $t= $this->FutureTweet->field('id', array('release_date ' => $current_time), '');
      $this->FutureTweet->delete( $t );
      
    endforeach;
  }



  /**
   * Given a tweetid, this function checks the permission level of the current user. If he is either an admin or 
   * moderator, then the tweet with the supplied id is deleted from the database if such a tweet exists. If it
   * doesn't exist, the user is informed that the supplied tweet id belongs to a tweet that does not exist.
   * @param $id the id of the tweet to be deleted.
   * @return void
   * @author Kareem Yousry
   */

  public function delete($id = NULL) {
    
    $userID = $this->Auth->User('userID');
    $accID = $this->Auth->User('accID');

    if($this->User->getPermissionLevel($accID, $userID) == 3 OR $this->User->isAdmin($userID))
    {
      if($this->FutureTweet->delete($id)) {
          $this->Session->setFlash('This Tweet has been deleted successfully.');
          $this->redirect(array('action' => 'index'));

        } else {
          $this->Session->setFlash('The supplied tweet does not exist.');
          $this->redirect(array('action' => 'index'));
        }
    } else {
        $this->Session->setFlash('You are not authorized to delete this tweet');
        $this->redirect(array('action' => 'index'));
    }
  }

  /**
   * Giveen a tweet id, this function either approves the specified tweet, disproves the tweet or
   * specifies that the entered tweet does not exist. If the user lacks sufficient privilleges, 
   * he is notified that he is not authorized to carry out such an action.
   * @param  int $id The specified tweet id.
   * @return void     Only a flash is shown.
   * @author KareemYousry
   */
  public function approveTweet($id){
    $accID = $this->Auth->User('accID');
    $userID = $this->Auth->User('userID');

    if($this->User->getPermissionLevel($accID, $userID) == 3 OR $this->User->isAdmin($userID)) {
      $result = $this->FutureTweet->approve($id);

      switch($result) {
        case '0':
          $this->Session->setFlash('Tweet has been approved successfully');
          $this->redirect(array('action' => 'index'));
          break;

        case '1':
          $this->Session->setFlash('Tweet has been disproved succesfully');
          $this->redirect(array('action' => 'index'));
          break;

        case '2':
          $this->Session->setFlash('The specified Tweet does not exist');
          $this->redirect(array('action' => 'index'));
          break;
      }
    } else {
        $this->Session->setFlash('You are not authorized to approve this tweet');
        $this->redirect(array('action' => 'index'));
    }

  }
  
  

/*
 * Description of "viewfuturetweets"
 * @param  "userid","accountid" 
 *
 *This function is for any user to view his future tweets on a certain account (the tweets that haven't been sent).
 *
 * @author "Ahmed El-Fouly"
 */
	public function viewfuturetweets() {
    
		$userID = $this->Auth->User('userID');
		$accID = $this->Auth->User('accID');
    if($this->User->getPermissionLevel($accID, $userID) ==1){
		$this->set('futureTweets', $this->FutureTweet->find('all', array('conditions' => array("FutureTweet.userID" => $userID, "FutureTweet.accID" => $accID))));
    }
    else{
      $this->Redirect('/FutureTweets/index1');
    }	
  }
/*
 * Description of "viewfuturetweets"
 * @param  "userid","accountid" 
 *
 *This function is for any user to edit his future tweets on a certain account (the tweets that haven't been sent).
 *
 * @author "Ahmed El-Fouly"
 */
	public function edittweets($id = null) {
        $this->FutureTweet->id = $id;
        $tweetUserID = $this->FutureTweet->find('first', Array('conditions' => array('id' => $id), 'fields' => array('userID')));
        $userID = $this->Auth->User('userID');
        if ($tweetUserID['FutureTweet']['userID'] != $userID) {
            $this->Session->setFlash("You're only authorized to edit your tweets, and please use our interface.");
            $this->redirect(array('action' => 'viewfuturetweets'));
        }
        if (empty($this->data)) {
            $this->data = $this->FutureTweet->read();
        } else {
            $length = strlen($this->data['FutureTweet']['tweetText']);
            if ($length == 0) {
                $this->Session->setFlash("Your tweet can't be null");
                return $this->redirect(array('action' => 'edittweets', $id));
            }
            if ($length > 140) {
                $this->Session->setFlash("Your tweet can't exceed 140 characters");
                return;
            }
            $accountID = $this->Auth->User('accID');
            $userID = $this->Auth->User('userID');
            $permission = $this->User->getPermissionLevel($accountID, $userID);
            if ($permission == 1) {
                $this->data = $this->FutureTweet->updateapprovedfalse($this->data);
            }
            if ($this->FutureTweet->save($this->data)) {
                $this->Session->setFlash('Your tweet has been edited.');
                $this->redirect(array('action' => 'viewfuturetweets'));
            }
        }
    }
	
    /*
     * Description of "PostTweet"
	 * @return: void Only set flash
     * description of the function : function post tweet is able to load the posts of the editor
      on the future timeline and also  save them in the database
     * @author "Amr Magdy"
     */

	public function PostTweet() {
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $current_time = date('Y-m-d H:i:s');

        if ($this->User->getPermissionLevel($accID, $userID) > 1 OR $this->User->isAdmin($userID) == 1) {
            if (!empty($this->request->data)) {
                $text = "" . ($this->request->data['FutureTweet']['tweetText']);

                $tweet = array(
                    'release_date' => $current_time,
                    'sub_time' => $current_time,
                    'userID' => $userID,
                    'accID' => $accID,
                    'tweetText' => $text,
                    'approved' => 1,
                );
                if (strlen($text) == 0) {

                    $this->Session->setFlash('Write something First');
                }
                
                switch($this->FutureTweet->insertTweet($tweet)){
                    
                    case 0:
                        $this->Session->setFlash('Tweet was added Successfully');
                            break;
                        case -1:
                            $this->Session->setFlash('This Tweet is a duplicate .please change the text');
                            break;
                        case -2:
                            $this->Session->setFlash('You have violated the Minimum time duration please try again later');
                            break;
                        case -3:
                            $this->Session->setFlash('Internal Error');
                            break;
                }
                
                $this->redirect(array('action' => 'index'));
            }
        }
        else{
            if($this->User->getPermissionLevel($accID, $userID) == 1){
            
            if (!empty($this->request->data)) {
                $text = "" . ($this->request->data['FutureTweet']['tweetText']);

                $tweet = array(
                    'release_date' => $current_time,
                    'sub_time' => $current_time,
                    'userID' => $userID,
                    'accID' => $accID,
                    'tweetText' => $text
                );

                if (strlen($text) == 0) {

                    $this->Session->setFlash('Write something First');
                }

                switch($this->FutureTweet->insertTweet($tweet)){
                    
                    case 0:
                        $this->Session->setFlash('Tweet was added Successfully');
                            break;
                        case -1:
                            $this->Session->setFlash('This Tweet is a duplicate .please change the text');
                            break;
                        case -2:
                            $this->Session->setFlash('You have violated the Minimum time duration please try again later');
                            break;
                        case -3:
                            $this->Session->setFlash('Internal Error');
                            break;
                }
                $this->redirect(array('action' => 'index'));
            }
        }
        else 
        {
            $this->Session->setFlash('You are not authorized to post tweets');
        }
        }
    }
     /*
     * Description of "PostTweetLater"
	 * @return: void   Only set flash
     * description of the function : function post tweet is able to load the posts of the editor
      on the future timeline with the date the posts will be posted on twiiter and also  save
      them in the database
     * @author "Amr Magdy"
     */

    public function PostTweetLater() {
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');

        if ($this->User->getPermissionLevel($accID, $userID) > 1 OR $this->User->isAdmin($userID) == 1) {
            if (!empty($this->request->data)) {
                $text = "" . ($this->request->data['FutureTweet']['tweetText']);
                $date1 = ($this->request->data['FutureTweet']['release_date']);
                
                $date = $date1['year'] . '-' . $date1['month'] . '-' . $date1['day'] . ' ' . $date1['hour'] . '-' . $date1['min'] . '-00';

                $tweet = array(
                    'release_date' => $date,
                    'sub_time' => $date,
                    'userID' => $userID,
                    'accID' => $accID,
                    'tweetText' => $text,
                    'approved' => 1
                );

                if (strlen($text) == 0) {

                    $this->Session->setFlash('Write something First');
                }

                switch($this->FutureTweet->insertTweet($tweet)){
                    
                    case 0:
                        $this->Session->setFlash('Tweet was added Successfully');
                            break;
                        case -1:
                            $this->Session->setFlash('This Tweet is a duplicate .please change the text');
                            break;
                        case -2:
                            $this->Session->setFlash('You have violated the Minimum time duration please try again later');
                            break;
                        case -3:
                            $this->Session->setFlash('Internal Error');
                            break;
                }
                
                $this->redirect(array('action' => 'index'));
            }
        }
        else{
            if($this->User->getPermissionLevel($accID, $userID) == 1){
                
                if (!empty($this->request->data)) {
                $text = "" . ($this->request->data['FutureTweet']['tweetText']);
                $date1 = ($this->request->data['FutureTweet']['release_date']);
                
                $date = $date1['year'] . '-' . $date1['month'] . '-' . $date1['day'] . ' ' . $date1['hour'] . '-' . $date1['min'] . '-00';

                $tweet = array(
                    'release_date' => $date,
                    'sub_time' => $date,
                    'userID' => $userID,
                    'accID' => $accID,
                    'tweetText' => $text
                );

                if (strlen($text) == 0) {

                    $this->Session->setFlash('Write something First');
                }

                switch($this->FutureTweet->insertTweet($tweet)){
                    
                    case 0:
                        $this->Session->setFlash('Tweet was added Successfully');
                            break;
                        case -1:
                            $this->Session->setFlash('This Tweet is a duplicate .please change the text');
                            break;
                        case -2:
                            $this->Session->setFlash('You have violated the Minimum time duration please try again later');
                            break;
                        case -3:
                            $this->Session->setFlash('Internal Error');
                            break;
                }
                $this->redirect(array('action' => 'index'));
            }
            }
        
        else 
        {
            $this->Session->setFlash('You are not authorized to post tweets');
        }
        }
    }
  
  
      /*
     * Description of "viewScheduledTweet"
     * @param : accID , userID
	 * @return: void   Only set flash
     * description of the function : is able to select the user hwa wants to view his posts 
     * @author "Amr Magdy"
     */

    public function viewScheduledTweet($accID = null, $userID = null) {
       if($this->FutureTweet->getUser1($accID, $userID)== array()){
            
            $this->Session->setFlash('There are no tweets made yet by this user');
            
        }
        $this->set('result', $this->FutureTweet->getUser1($accID, $userID));
    }

     /*
     * Description of "viewScheduledTweet1"
     * @param : accID , userID
	 * @return: void   Only set flash
     * description of the function : it gets the editor's and J.editor's tweets  
     * @author "Amr Magdy"
     */

    public function viewScheduledTweet1($accID = null, $userID = null) {
        
        if($this->FutureTweet->getUser1($accID, $userID)== array()){
            
            $this->Session->setFlash('There are no tweets made yet by this user ');
            
        }
        $this->set('result', $this->FutureTweet->getUser1($accID, $userID));
    }
   
   	
   
      /*
     * Description of approve
     * @param : id
     * moderator is able to approve j.e tweets
     *@return: void   Only set flash
     * @author Amr Magdy
     */

    public function approve($id = null) {

        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        
        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == true) {

            if (!$this->FutureTweet->tweetExists($id)) {
                $this->Session->setFlash('The Supplied tweet does not exist');
                $this->redirect(array('action' => 'index'));
            }

            if ($this->FutureTweet->isApprove($id) == 1) {
                $this->Session->setFlash('This Tweet is Already approved.');
                $this->redirect(array('action' => 'index'));
            } else {

                $this->FutureTweet->ApproveTweet($id, 1);
                $this->Session->setFlash('The Tweet has been approved successfuly.');
                $this->redirect(array('action' => 'index'));
            }
        } else {
            $this->Session->setFlash('You are not authorized to Approve this Tweet');
            $this->redirect(array('action' => 'index'));
        }
    }

   /*
     * Description of reject
     * @param : id
     * moderator is able to reject j.e tweets
     * @return: void   Only set flash
     * @author Amr Magdy
     */

    public function reject($id = null) {

         $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');

        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == true) {

            if ($this->FutureTweet->isrejected($id) == 2) {
                $this->Session->setFlash('This Tweet is Already rejected.');
                $this->redirect(array('action' => 'index'));
            } else {

                $this->FutureTweet->RejectTweet($id, 2);
                $this->Session->setFlash('The Tweet has been rejected successfuly.');
                $this->redirect(array('action' => 'index'));
            }
        } else {
            $this->Session->setFlash('You are not authorized to Reject this Tweet');
            $this->redirect(array('action' => 'index'));
        }
    }
	
	/*
     * Description of viewApproved1
     * editor/j,editor is able to view approved tweets
     * @return: void   Only set flash
     * @author Amr Magdy
     */

    public function viewApproved1(){
        
         if($this->FutureTweet->approvedTweets()== array()){
            
            $this->Session->setFlash('There are no  approved tweets');
        }
        
        $this->set('amr', $this->FutureTweet->approvedTweets());
    }
       
        /*
     * Description of viewApproved
     * moderator is able to view approved tweets
     * @return: void   Only set flash
     * @author Amr Magdy
     */

    public function viewApproved() {

        $accID = $this->Auth->User('accID');
        $userID = $this->Auth->User('userID');
        $this->set('accid', $accID);
        $this->set('num', $this->FutureTweet->countPendingTweets());

        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == 1) {

            $user = new User;
            $this->set('e', $user->getEditorsByNameandid($accID));
            $this->set('je', $user->getJEditorsByNameandid($accID));
        } else {
            $this->redirect(array('action' => 'index1'));
        }
        
         if($this->FutureTweet->approvedTweets()== array()){
            
            $this->Session->setFlash('There are no  approved tweets');
        }

        $this->set('amr', $this->FutureTweet->approvedTweets());
    }
	
	/*
     * Description of viewRejected1
     * editor or j.editor is able to view rejected tweets
     * @return: void   Only set flash
     * @author Amr Magdy
     */

     public function viewRejected1(){
        
        if($this->FutureTweet->rejectedTweets()== array()){
            
            $this->Session->setFlash('There are no  rejected tweets');
        }
        
        $this->set('rejected', $this->FutureTweet->rejectedTweets());
    }
       
      /*
     * Description of viewRejected
     * moderator is able to view rejected tweets
     * @return: void   Only set flash
     * @author Amr Magdy
     */

    public function viewRejected() {

        $accID = $this->Auth->User('accID');
        $userID = $this->Auth->User('userID');
        $this->set('accid', $accID);
        $this->set('num', $this->FutureTweet->countPendingTweets());

        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == 1) {

            $user = new User;
            $this->set('e', $user->getEditorsByNameandid($accID));
            $this->set('je', $user->getJEditorsByNameandid($accID));
        } else {
            $this->redirect(array('action' => 'index1'));
        }
        
        if($this->FutureTweet->rejectedTweets()== array()){
            
            $this->Session->setFlash('There are no  rejected tweets');
        }

        
        $this->set('rejected', $this->FutureTweet->rejectedTweets());
    }
	
	/*
     * Description of viewPending1
     * editor or j.editor is able to view tweets not approved nor rejected yet
     * @return: void   Only set flash
     * @author Amr Magdy
     */

     public function viewPending1(){
        
        if($this->FutureTweet->pendingTweets()== array()){
            
            $this->Session->setFlash('There are no  pending tweets');
        }
        
        $this->set('pending', $this->FutureTweet->pendingTweets());
        
    }

    /*
     * Description of viewPending
     * moderator is able to view tweets not approved nor rejected yet
     * @return: void   Only set flash
     * @author Amr Magdy
     */

     public function viewPending() {

        $accID = $this->Auth->User('accID');
        $userID = $this->Auth->User('userID');
        $this->set('accid', $accID);
        $this->set('num', $this->FutureTweet->countPendingTweets());

        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == 1) {

            $user = new User;
            $this->set('e', $user->getEditorsByNameandid($accID));
            $this->set('je', $user->getJEditorsByNameandid($accID));
        } else {
            $this->redirect(array('action' => 'index1'));
        }
        
        if($this->FutureTweet->pendingTweets()== array()){
            
            $this->Session->setFlash('There are no  pending tweets');
        }

        $this->set('pending', $this->FutureTweet->pendingTweets());
    }
	
	/*
     * Description of viewAll1
     * editor or j.editor is able to view all tweets
     * @return: void   
     * @author Amr Magdy
     */

    public function viewAll1(){
        
        $this->redirect(array('action' => 'index1'));
        
    }

    /*
     * Description of viewAll
     * moderator is able to view all tweets
     * @return: void   
     * @author Amr Magdy
     */

    public function viewAll() {

        $this->redirect(array('action' => 'index'));
    }

    /*
     * Description of viewMyTweets
     * @param :userID
     * editor or j.editor is able to view his own tweets
     * @return: void   Only set flash
     * @author Amr Magdy
     */

    public function viewMyTweets($userID = null) {

        $userID = $this->Auth->User('userID');
        
        if($this->FutureTweet->MyTweets($userID)== array()){
            
            $this->Session->setFlash('There are no tweets made yet ');
            
        }

        $this->set('x', $this->FutureTweet->MyTweets($userID));
    }

    /*
     * @access: public
     * @param: $resultMessage
     * Description: Uses the $resultMessage variable and based
     * on it's value it sets a different flash message
     * @author Ahmed El-Fouly
     */
    public function flashes($resultMessage) {
        if ($resultMessage == 0) {
            $this->Session->setFlash("Done, and waiting for the moderator's approval.");
        } else {
            if ($resultMessage == -1) {
                $this->Session->setFlash('Tweet already exists and waiting for the moderators approval.');
            } else {
                if ($resultMessage == -2) {
                    $this->Session->setFlash("The minimum duration didn't hold, give it a couple of seconds, then try again");
                } else {
                    if ($resultMessage == -3) {
                        $this->Session->setFlash("An unknown error occured, please try again.");
                    }
                }
            }
        }
    }
    /*
     * @access: public
     * @param: $postID, $home, $userID, $accID
     * Description: gets the information needed like userID, accID, current_time
     * and executes the model function that insert them in the database table (future_tweets) and redirects
     * to the dashboard or home timeline, based on the $home variable
     * @author Ahmed El-Fouly
     */
    public function retweet($postID, $home, $userID, $accID) {
        $current_time = date('Y-m-d H:i:s');
        $this->loadModel('Post');
        $this->loadModel('User');
        if ($home == 0) { //Checks if this function is called from the dashboard view
            $text = "RT: " . $this->Post->getPostText($postID);
            $tweet = array(
                'release_date' => $current_time,
                'userID' => $userID,
                'accID' => $accID,
                'tweetText' => $text,
                'approved' => false
            );
            $this->flashes($this->FutureTweet->insertTweet($tweet)); //Inserts it in the future_tweets table
                                                                     // then calls function flashes 
                                                                     // with the returned message
            $this->redirect(array('controller' => 'posts', 'action' => 'index'));
        }
        if ($home == 1) { //Checks if this function is called from the Home Timeline view
            $tempAccount = new Account();
            $connection = $tempAccount->connectionRequest($accID);
            if($connection == false) {
                $this->Session->setFlash("Something went wrong while connecting to twitter.");
                return;
            }
            $post = (array) $connection->get('statuses/show/' . $postID);
            $postText = $post['text'];
            $user = (array) $post['user'];
            $text = "RT @" . $user['screen_name'] . ": " . ($postText);
            $tweet = array(
                'release_date' => $current_time,
                'userID' => $userID,
                'accID' => $accID,
                'tweetText' => $text,
                'approved' => false
            );
            $this->flashes($this->FutureTweet->insertTweet($tweet));//Inserts it in the future_tweets table
                                                                     // then calls function flashes 
                                                                     // with the returned message
            $this->redirect(array('controller' => 'posts', 'action' => 'fetchHome'));
        }
    }
		
	/**
     * Description of function "DeleteTweetForJE"
     * @param string $TweetID
     * 
     *
     * Description:
     * The function takes the tweet ID deletes it from the database, if it still exists
     * @author "Mark Milad"
     */
    public function DeleteTweetForJE($tweetID){
        if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
        }

          if($this->FutureTweet->deleteJETweet($tweetID) == true)
      {
               $this->Session->setFlash('Successfully deleted');
               $this->redirect(array('action'=>'viewfuturetweets'));
               
      }
      else {
        $this->Session->setFlash('Oops .. looks like your tweet does not exist anymore, may have been deleted or approved by a moderator or an admin');
        $this->redirect(array('action'=>'viewfuturetweets'));
      }
        
        
    } 

     /*
 * Description of save1
 * @param  "id"
 * 
 *
 *this function freeze the tweet when its being edit so it wont be posted on twitter while it is being edited 
 *
 *@return void
 *
 * @author "Youssef Madkour"
 */


    public function save1($id= null){

        $t = $this->FutureTweet->find('first',array('FutureTweet.id'=>$id));
        $saved = $t['FutureTweet']['saved'];

        $this->id = $id;
         $this->FutureTweet->updateAll(
                    array('saved' => '1'),
                    array('id' => $id));
        $this->redirect(array('controller'=>'FutureTweets','action'=>'editModerator', $id));


    }
    /*
 * Description of editModerator
 * @param  "id"
 *
 *Y: the function will let the moderator to edit any tweet only in the accounts, that is assigned to him.
 *
 *A: and checking that the input given is in the correct syntax, and format, and is possibly true.
 *
 *@return void
 *
 * @author "Youssef Madkour", "Ahmad AboulAzm"
 */
    

   public function editModerator($id = null) {
        //$this->FutureTweet->id=$id;
        if(empty($this->data)) {
            $this->data = $this->FutureTweet->read(Null,$id);
        }
         else {

            $accountID=$this->Auth->User('accID');
            $userID=$this->Auth->User('userID');
            $permission =$this->User->getPermissionLevel($accountID,$userID);

            $data = $this->request->data['FutureTweet']['release_date'];
            
            if($permission == 3 ||$this->Auth->User('admin')==1) {

                list($Year, $Month, $Day, $Clock) = split('[ .-]', $data);
                list($Hour, $Minute, $Second) = split('[:.-]', $Clock);
                // print_r($Year);
                // print_r($Month);
                // print_r($Day);
                // print_r($Hour);
                // print_r($Minute);
                // print_r($Second);

                // if(empty($Date) OR empty($Clock))
                // {
                //     $this->Session->setFlash('Wrong date and time Input');
                //     return;
                // }

                // list($Year, $Month, $Day) = split('[-.-]', $Date);
                // list($Hour, $Minute, $Second) = split('[:.-]', $Clock);

                $current_time = date('Y-m-d H:i:s');
                list($CYear, $CMonth, $CDay, $CClock) = split('[ .-]', $current_time);
                //list($CYear, $CMonth, $CDay) = split('[-.-]', $CDate);
                list($CHour, $CMinute, $CSecond) = split('[:.-]', $CClock);


                if(strtotime($data) < strtotime($current_time))
                {
                    $this->Session->setFlash('The Release time for this tweet has already passed');
                    return;
                }

                if((empty($Year))OR(empty($Month))OR(empty($Day))OR(empty($Hour))OR(empty($Minute))OR(empty($Second)))
                {
                    $this->Session->setFlash('Wrong time input');
                    return;
                }

                if((!(is_numeric($Year)))OR(!(is_numeric($Month)))OR(!(is_numeric($Day)))OR(!(is_numeric($Hour)))OR(!(is_numeric($Minute)))OR(!(is_numeric($Second))))
                {
                    $this->Session->setFlash('Please enter date and time in form of numbers');
                    return;   
                }

                if((!((0 < $Month) && ($Month < 13))) OR (!((0 < $Day) && ($Day < 32))) OR (!((-1 < $Hour) && ($Hour < 24))) OR (!((-1 < $Minute) && ($Minute < 60))) OR (!((-1 < $Second) && ($Second < 60))))
                {
                    $this->Session->setFlash('Wrong Input, Please enter input within the correct interval');
                    return;   
                }
                
               
                $old = $this->FutureTweet->find('first',array('conditions'=>array('FutureTweet.id'=>$id)));
                       $tweet = array('userID' => $this->data['FutureTweet']['userID'], 'tweetText' => $this->data['FutureTweet']['tweetText'],
                'eventID' => $this->data['FutureTweet']['eventID'], 'approved' => $this->data['FutureTweet']['approved'],
                'release_date' => $this->data['FutureTweet']['release_date'],'accID' => $this->data['FutureTweet']['accID']); 
                    $this->FutureTweet->delete($id);
                    $message = $this->FutureTweet->insertTweet($tweet);

                    switch ($message) {
                        case 0:
                             echo 'Tweet has been eddited Successfully';
                            break;
                        case -2:
                            echo 'You have violated the Minimum time duration please change the date';
                            $tweet = array('userID' => $old['userID'], 'tweetText' => $$old['tweetText'],
                                  'eventID' => $old['eventID'], 'approved' => $old['approved'],
                                  'release_date' => $old['release_date'],'accID' => $old['accID']); 
                            $this->FutureTweet->insertTweet($tweet);
                            break;
                        case -3:
                            echo 'Internal Error';
                            $tweet = array('userID' => $old['userID'], 'tweetText' => $$old['tweetText'],
                                  'eventID' => $old['eventID'], 'approved' => $old['approved'],
                                  'release_date' => $old['release_date'],'accID' => $old['accID']); 
                            $this->FutureTweet->insertTweet($tweet);
                            break;
                    }

                    if($message == 0)
                    {
                      
                     $t = $this->FutureTweet->find('first',array('conditions' =>array('FutureTweet.tweetText'=>$this->data['FutureTweet']['tweetText'],
                      'FutureTweet.accID'=>$this->data['FutureTweet']['accID'],
                      'FutureTweet.release_date'=>$this->data['FutureTweet']['release_date'],
                      'FutureTweet.eventID'=>$this->data['FutureTweet']['eventID'],
                      'FutureTweet.userID'=>$this->data['FutureTweet']['userID'])));

                    
                    $this->FutureTweet->updateAll(
                    array('saved' => '0'),
                    array('id' => $t['FutureTweet']['id']));


                       $this->redirect(array('action'=>'index', $id));
                        
                    }
            }

                else{
                    
                        $this->Session->setFlash('You are not allowed to edit this tweet');
                    $this->redirect(array('action'=>'index', $id));
                }
        }
    }
}